// components/general_entity/general_entity.js

/**
 * 多处这样的调用是为了阻止字段修改触发方法导致死循环
 * this.setData({isEdit: true}); 阻止触发修改
  this.setData({defData: **});
  this.setData({isEdit: false}); 恢复触发
 */
let referenceBehavior = require('./reference');
let calculateBehavior = require('./calculate');
Component({
  behaviors: [ referenceBehavior,calculateBehavior, ],
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
//
  /**
   * 组件的属性列表
   */
  properties: {
    //模块id
    entity: { //表id
      type: String,
      value: '',
      observer(newVal){
        this.initData(newVal);
      }
    },
    //模块参数
    entityParam:{
      type: Object
    },
    status:{type: String},
    //行号
    rowId: {
      value: '',
      observer(id){
        if (this.data.entity && !['',false,null,undefined].includes(id)){
          if (id === 0) {//清空数据
            this.setData({isEdit: true});
            let obj = wx.$extend(this.data.defValue);
            this.setData({
              inputData: {
                entity: obj,
                details: []
              },
              defData: obj,
              defDetail: {}
            });
            this.setData({isEdit: false});
            this.triggerBtnType('edit');

          }else {
            id && this.getRowData(id);
          }
        }
      }
    },
    //行数据
    rowData: {
      type: Object,
      observer(newVal){
        if (!newVal)return;
        if (Object.keys(newVal).length) {
          this.formatData(newVal);
        }else{
          //新增
          let obj = wx.$extend(this.data.defValue);
          this.setData({isEdit: true});
          this.setData({
            inputData: {
              entity: {row_id: 0,...obj},
              details: []
            },
            defData: obj,
            defAssist: ''
          });
          this.setData({isEdit: false});
        }
      }
    },
    defVal: {
      type: Object,
      observer(val){
        this.data.defValue = {...this.data.defValue,...val};
      }},
    //明细布局数据
    layout:{
      type: Array,
      observer(val){if (val)this.data.tableLayout = val;/*this.setData({tableLayout: val});*/}
    },
    authority:{
      type: Object,
      observer(val){
        if (val) this.setData({ auth: val });}
    },
    //顶部返回按钮
    returnIcon: {
      type: Boolean,
      value: false
    },
    //录入提交
    inputData: {
      type: Object,
      value: {
        entity: {},
        details: []
      }
    },
    //只读-页面只读，明细只读
    readonly: {
      type: Boolean,
      observer(val){
        if (val) {
          this.setData({
            isEdit: true
          });
          this.triggerBtnType('read');
        }else {
          this.triggerBtnType('edit');
        }
      }
    },

    //是否新增审批
    approve: {
      type: Boolean,
      observer(bool){
        setTimeout(()=>{
          /*this.setData({
            scrollId: 'bottomId'
          });*/
          console.log(bool);
          if (bool){
            this.triggerBtnType('approve');
          } else {
            this.triggerBtnType('read');

          }
        },300)
      }
    },
    fieldInfo: {},  //字段信息
    expList: { //计算公式
      observer(val){
        if (val){
          this.initExpData();
        }
      }
    },

    //主表修改引用字段值触发修改明细表过滤条件
    mainEntityFields:{
      type: Array,
      observer(val){
        if (!val.length)return;
        let {parMainEntity,tableLayout} = this.data,
          fieldObj = {};
        if (!parMainEntity)return;

        wx.$each(val,(i,item)=>{
          let {mainEntity,rowid} = item;

          if (parMainEntity[mainEntity]){
            wx.$each(parMainEntity[mainEntity],(ind,ite)=>{
              fieldObj[ite] = rowid;
            })
          }
        });

        if (Object.keys(fieldObj).length){
          //查找过滤主表字段
          tableLayout.map(item=>{
            item.field && item.field.map(ite=>{
              let filedid = ite.field_id || ite.fieldName;
              if (fieldObj[filedid] !== undefined) {
                ite.referenceFilterCondition = this.setReferenceCondition(fieldObj[filedid],"parent_row_id",ite.referenceFilterCondition)
              }
            })
          });

          this.setData({isEdit: true});
          this.setData({tableLayout});
          this.setData({isEdit: false});
        }

      }
    },

  },

  /**
   * 监听数据
   */
  observers:{
  },

  /**
   * 组件的初始数据
   */
  data: {
    tableName: '',  //模块名
    detailInfo: [],  //明细表信息{table_id,table_name,layout:明细布局，is_open: 是否展明细}

    validFlag: false,             // 验证标识
    validObj: {},                 // 验证表单项

    defData:{}, //显示数据
    defDetail: [],  //显示明细数据
    editBtn: false, //编辑按钮
    saveBtn: true,  //保存按钮
    newBtn: true,    //保存新增按钮

    dtlMapping: [],  //主表映射明细表
    dtlMapField: [],
    detailMapVal: {}, //主表映射明细数据

    BomGoods: {},  //bom商品信息

    isEdit: true,


    //滚动到指定位置
    scrollId: '',

    fieldProperties: {},//字段关系

    //辅助核算科目id
    accountId: '',
    defAssist: '',


  },

  /**
   * 组件的方法列表
   */
  methods: {
    //初始化
    async initData(entity){
      wx.showLoading({mask: true});
      this.data.tableLayout = null
      this.data.fieldInfo = null
      // !this.data.auth && 
      await wx.$getAuth(entity).then(res=>{
        this.setData({auth: res});
      });
      await this.getFieldAll(entity);
      await this.getTableInfo(entity);

      if (this.data.rowId) {
        this.getRowData(this.data.rowId);
      }
      wx.hideLoading();
    },
    //格式化传入数据
    formatData(data,isInit){
      if (!data)return;
      if (data.details){
        let mainData = data.entity,
          obj = {row_id: mainData.row_id},
          showEntity = data.showEntity || data.entity,
          showDetails = data.showDetails || data.details;
        let setObj = {
          inputData: {entity: obj,details: data.details},
          defData: showEntity,
          defDetail: showDetails
        };
        //格式化辅助核算显示内容
        if (showEntity.assist_account_json) {
          let assistJson = JSON.parse(showEntity.assist_account_json);
          showEntity.assist_account_json = assistJson.name;
          setObj.defAssist = assistJson;
        }
        showEntity.account_id && (setObj.accountId = showEntity.account_id);

        //编辑-初始根据主表过滤明细表数据
        let myDefMainEntity = this.data.myDefMainEntity,
          myMainEntity = [];
        wx.$each(myDefMainEntity,(key,val)=>{
          wx.$each(val,(i,item)=>{
            myMainEntity.push({
              mainEntity: key,
              rowid: showEntity[item] || ''
            })
          })
        });
        myMainEntity.length && (setObj.myMainEntity = myMainEntity);

        //编辑-初始主表映射明细表
        this.setDtlMapping(showEntity);

        this.setData({isEdit: true});
        this.setData(setObj);
        if (!this.data.readonly) this.setData({isEdit: false});
      } else {
        this.getRowData(data.entity.row_id);

      }
    },

    //获取行数据
    getRowData(id){
      let url = 'DynamicQuery/query_dynamic_v2',
        post = {
          table_id: this.data.entity,
          row_id: id
        };
      wx.$post(3,url,post).then((res)=>{
        if (res.errcode != 0)return;
        let row = res.data.row;
        if (row && row[0]){
          let data = row[0];
          if (!data)return;
          let mainData = data.entity && data.entity[0],
            detail1 = data.detail1,
            detail2 = data.detail2;
          let obj = {
              entity: {row_id: mainData.row_id},
              details: [],
              showEntity: mainData,
              showDetails: []
            };
            if (detail1.entity && detail1.entity[0]){
              let arr = detail1.entity,
                entitys = [],
                show = [];
              wx.$each(arr,(i,item)=>{
                entitys.push({entity: {row_id: item.row_id}, details: []});
                show.push({entity: item, details: []});
              });
              obj.details.push({
                table_id: detail1.table_id,
                entitys: entitys
              });
              obj.showDetails.push({
                table_id: detail1.table_id,
                entitys: show
              });
            }
            if (detail2.entity && detail2.entity[0]){
              let arr = detail2.entity,
                entitys = [],
                show = [];
              wx.$each(arr,(i,item)=>{
                entitys.push({
                  entity: {row_id: item.row_id},
                  details: []
                });
                show.push({
                  entity: item,
                  details: []
                });
              });
              obj.details.push({
                table_id: detail2.table_id,
                entitys: entitys
              });
              obj.showDetails.push({
                table_id: detail2.table_id,
                entitys: show
              })
            }
          this.formatData(obj)
        }
      })
    },

    //获取模块信息
    async getTableInfo(table){
      let url = 'Custom/select_entity_detailed',
        post = {"table_type":"","table_id": table};
      // 230114 yan 注释
      // await this.getFieldProperties();
      await this.getStockEntity();
      return new Promise((resolve => {
        wx.$post(1,url,post).then(async (res)=>{
          if (res.errcode != 0){
            resolve();
            return
          }
          let data = res.data,
            data0 = data && data.row[0],
            data1 = data && data.row[1],
            mainData = {},
            tableName,tableType;
          if (data1){
            mainData = data1;
            tableName = data1.table_name;
            tableType = data1.table_type;
          } else {
            if (data0.table_id === table) {
              mainData = data0;
              tableName = data0.table_name;
              tableType = data0.table_type;
            }else {
              tableName = data0.table_name_mx;
              tableType = data0.table_type_mx;
            }
          }
          this.data.tableType = tableType;
          this.setData({
            tableName: tableName || '',
            tableType
          });
          //主表
          if (!this.data.tableLayout) {
            let layout = '';
            await this.getLayoutJson(table).then((data)=>{
              layout = data && data.html_js || '';
              try {
                layout = JSON.parse(layout);
              }catch (e) {}
              wx.$each(layout,(i,item)=>{
                let fields = item.field;
                fields[0] && wx.$each(fields,(ind,ite)=> {
                  let id = ite.field_id || ite.fieldName,
                    opt = this.data.fieldInfo.find(item=>{
                      if (item.field_id === id){
                        if (item.type === 'picture'){
                          item.watermark = [{
                            content: '$time$',
                            font: '34px sans-serif',
                            lineWidth: 3,
                            position: {
                              bottom: 15,
                              left: 15
                            }
                          },
                            {
                              content: '$location$',
                              font: '28px sans-serif',
                              lineWidth: 3,
                              position: {
                                bottom: 60,
                                left: 15
                              }
                            },]
                        }
                        return true
                      }
                    });
                  if (!opt){return}
                  fields[ind] = opt;
                });
              });
              this.data.tableLayout = layout;
              /*this.setData({
                tableLayout: layout
              });*/
            });
          }

          this.getDefValue();


          if (mainData.table_id_mx && table === mainData.table_id) {  //有明细
            let mxId = mainData.table_id_mx.split(','),
              mxName = mainData.table_name_mx.split(','),
              arr = [];

            for (let i = 0;i<mxId.length;i++) {
              let obj = {
                table_id: mxId[i],
                table_name: mxName[i],
                layout: '',
                is_open: false
              };
              await this.getLayoutJson(mxId[i]).then((data)=>{
                let layout = data && data.html_js || '';
                try {
                  layout = JSON.parse(layout);
                }catch (e) {}

                obj.layout = layout;
              });
              arr.push(obj);
              this.getDtlMapping(this.data.entity,mxId[i])
            }
            this.setData({
              detailInfo: arr
            });

          }
          resolve();
        })
      }))
    },
    //获取布局
    getLayoutJson(tableid,fn){
      let url = 'Custom/get_html_WXMiniProgram',
        post = {'table_id': tableid};
      return new Promise((resolve => {
        wx.$post(1,url,post).then((res)=>{
          if (res.errcode != 0)return;
          let data = res.data.row && res.data.row[0];
          if (!data){
            let url2 = 'Custom/get_html'
            wx.$post(1,url2,post).then(res=>{
              if (res.errcode != 0)return;
              let data = res.data.row && res.data.row[0];
              resolve(data);
            });
            return
          }

          resolve(data);
        })
      }))
    },

    //获取所有字段
    getFieldAll(entity,fieldid){
      let url = 'QX/PRO_select_field',
        post = {
          "table": entity,
          "fieldname": fieldid
        };

      if(this.data.fieldInfo){
        return
      }
      return new Promise(resolve => {
        wx.$post(4,url,post).then((res)=>{
          if (res.errcode != 0)return;
          let data = res.data.row;
          let exp = [];
          wx.$each(data,function (i,item) {
            if (item.computeExpress) {
              exp.push(item);
            }
          });
          this.setData({
            fieldInfo: data,
            expList: exp
          });
          resolve();
        });
      })
    },

    //获取默认值、判断字段权限是否可录入
    async getDefValue(){
      let defObj = {},
        {tableLayout,status,auth,fieldProperties,rowId,rowData,expList,stockEntity,mainEntityFields,entity} = this.data;
      await this.getDefaultWarehouse();
      let collectionFields = [];
      await this.getCollentionField(entity).then(arr => collectionFields = arr)
      let myDefMainEntity = {},
        parMainEntity = {};
      wx.$each(tableLayout,async (i1,item1)=>{
        wx.$each(item1.field,(i2,item2)=>{
          let defV = '',defShow = '',
            hasRight = true,
            fieldid = item2.field_id || item2.fieldName,
            isStock = fieldid === 'reference1_goods' && stockEntity?.is_warehouse_first;

          item2.type = item2.type === 'bit' ? 'splc': item2.type;

          item2.isAppend = auth.fieldAppend.indexOf(fieldid)>=0;
          item2.isEdit = auth.fieldEdit;
          item2.isHide = auth.fieldSee.indexOf(fieldid)<0;
          isStock && (item2.filterTable = 'v_goods_balance');

          //映射是否可编辑--230114 yan 注释
          /*let properties = fieldProperties.find(item=>{
            return item.FieldName === fieldid
          });
          if (properties) {
            hasRight = properties.IsAllowModification;
          }*/
          //计算公式不可编辑
          if (expList.find(item=>{
            return item.field_id === fieldid
          })) {
            hasRight = false;
          }
          //出库模块，商品单价、成本不可输入
          if (stockEntity && stockEntity.stock_direction == 2 && ['goods_price','goods_unit_price'].includes(fieldid)) {
            hasRight = false;
          }
          if (collectionFields.includes(fieldid)) {
            hasRight = false;
          }

          item2.isDisabled = !hasRight;

          //特殊模块特别处理
          this.specialHandle(fieldid,item2);

          //禁止录入且必填，修改必填标识
          item2.is_null = item2.isDisabled ? true : item2.is_null;

          if (item2.defaultValue) {
            defV = item2.defaultValue;
          }
          //日期字段，默认值为当前时间
          if (item2.type === 'datetime' && defV === '$NOW$'){
            defV = wx.$util.formatDate(new Date(),item2.length || 'yyyy-MM-dd HH:mm')
            if (item2.length === 'yyyy-MM') {
              defV = defV + '-01'
            }else if (item2.length === 'yyyy') {
              defV = defV + '-01-01'
            }
          }
          //引用会计期
          if (item2.mainEntity === 'all_account_period') {
            let nowYear = new Date().getFullYear(),
              nowMonth = new Date().getMonth() + 1;
            nowMonth = nowMonth > 9 ? nowMonth : '0' + nowMonth ;
            defV = nowYear+''+nowMonth;
            defShow = defV
          }
          //引用仓库
          let defWarehouse = this.data.defWarehouse;
          if (item2.mainEntity === 'Warehouse' && defWarehouse){
            defV = defWarehouse.id;
            defShow = defWarehouse.name;
          }
          //商品引用字段，过滤仓库
          //240626 yan 注释，取消过滤仓库
          /*if (fieldid === 'reference1_goods' && defWarehouse) {
            /!*let filter = item2.referenceFilterCondition;
            let obj = filter && JSON.parse(filter);
            if (obj && obj.filters) {  //引用商品字段有过滤数据
              obj.filters.push(
                {"type":"AND","fieldName":"quote_Warehouse","value":defWarehouse.id,"operator":"="}
              )
            }else {
              obj = {"filters":[{"type":"AND","fieldName":"quote_Warehouse","value":defWarehouse.id,"operator":"="}],"type":"AND"}
            }
            item2.referenceFilterCondition = JSON.stringify(obj);*!/
            item2.referenceFilterCondition = this.setReferenceCondition(defWarehouse.id,"quote_Warehouse",item2.referenceFilterCondition)
          }*/
          //240626 end
          //单选、多选字段默认值
          if (item2.type === 'picklist' || item2.type === 'multiple'){
            let option = item2.option;
            try {
              option = JSON.parse(option)
            }catch (e) {}
            wx.$each(option,(i,item)=> {
              if (item.isDefault) {
                defV = item.label;
              }
            });
          }

          defV && (defObj[item2.field_id] = defV);
          defShow && (defObj[item2.field_id + ';value'] = defShow);

          //主表对应明细表映射
          if (item2.type === 'reference1' && item2.searchFields){
            parMainEntity[item2.searchFields] = parMainEntity[item2.searchFields] ? [...parMainEntity[item2.searchFields],fieldid] : [fieldid];

            if (mainEntityFields) {
              wx.$each(mainEntityFields,(i,item)=>{
                if (item.mainEntity === item2.searchFields){
                  item2.referenceFilterCondition = this.setReferenceCondition(item.rowid,"parent_row_id",item2.referenceFilterCondition)
                  return false;
                }
              });
            }
          }
          if (item2.type === 'reference1' && item2.mainEntity) {
            myDefMainEntity[item2.mainEntity] = myDefMainEntity[item2.mainEntity] ? [...myDefMainEntity[item2.mainEntity],fieldid] : [fieldid]
          }
        })
      });
      let obj = {
        tableLayout
      };
      if (!rowId && !rowData) { //新增
        defObj = {...this.data.defValue,...defObj};
        obj.inputData = {entity: {...defObj,row_id: 0},details: []};
        obj.defData= defObj;
        this.setData({isEdit: true});
        this.setData(obj);
        this.setData({isEdit: false});
      }else {
        this.setData(obj);
      }

      this.data.defValue = wx.$extend(defObj);
      this.data.parMainEntity = parMainEntity;
      this.data.myDefMainEntity = myDefMainEntity;
    },
    /**
     * 获取字段关系
     * kong wen jun 2022 06 02
     * @param {目标表} tableName
     */
    getFieldProperties() {
      let data={TableName: this.data.entity};
      return new Promise(resolve => {
        wx.$post(3,'Field_mapping/GetFieldProperties',data).then(res=>{
          if (res.errcode != 0)return;
          let item = res.data.row;
          this.data.fieldProperties = item;
          resolve();
        })
      })
    },

    /*获取归集字段*/
    getCollentionField(id){
      return new Promise(resolve => {
        let url = 'Field_value_collection/query_field_value_collection',
          post = {
            "page": 1,
            "limit": 1000,
            "oby": "collection_id",
            "SearchWhere": [{
              "CompareWith": "destination_table_id",
              "Operator": "=",
              "CompareValue": id,
              "or": 0
            }]
          },
          arr = [];
        wx.$post(3,url,post).then(res =>{
          if (res.errcode != 0){
            resolve(arr);
            return;
          }
          let data = res.data && res.data.row;
          data.forEach(item => {
            arr.push(item.destination_field_id);
          });
          console.log(arr);
          resolve(arr);
        })
      })
    },

    // 记录验证表单项
    validIpt(e) {

      let { validObj, } = this.data
      this.data.validObj = {
        ...validObj,
        ...e.detail,
      };
    },
    //验证数据
    validForm(validObj){
      return new Promise((resolve, reject) => {
        let assistValid = this.assistValid();
        let valid = assistValid && (Object.values(validObj).includes(false) ? false : true);
        resolve(valid)
      })
    },
    //展开收起分栏
    toggleSub(e){
      let index = e.currentTarget.dataset.index,
        key = 'tableLayout['+ index +'].is_open'
      this.setData({
        [key]: !this.data.tableLayout[index].is_open
      })
    },

    //取消关闭
    bindCancel(){
      this.triggerEvent(
        'cancel', //自定义事件名
      )
    },
    //编辑
    bindEdit(){
      if (!this.data.auth.tableEdit) {
        wx.$toast('抱歉，您没有权限编辑该模块数据！');
        return
      }
      this.setData({
        readonly: false
      });
      this.triggerEvent('beforeEdit')
    },
    //保存
    bindSave(e){
      // 开启验证
      this.data.validObj = {}
      this.setData({
        validFlag: !this.data.validFlag,
      });

      let type = e.currentTarget.dataset.type,
        formObj = this.data.inputData.entity,
        validObj = this.data.validObj;
      this.validForm(validObj).then(valid => {
        if(valid) { // 表单验证通过
          console.log('表单验证通过', formObj);
          if (type === 'saveNew'){
            this.setData({rowId: false,rowData: false})
          }
          this.triggerEvent(
            'save', //自定义事件名
            {data: this.data.inputData,defData: this.data.defData,defDetail: this.data.defDetail,isShow: type === 'saveNew'}
          )

        } else {  // 表单验证不通过
          console.log('表单验证不通过')
          wx.$toast('必填项不能为空！')
        }
      })
    },

    //清空
    clearInput(){
      this.setData({isEdit: true});
      this.setData({
        inputData: {entity: {...this.data.defValue,row_id: 0},details: []},
        defData: {...this.data.defValue},
        defDetail: {}
      });
      this.setData({isEdit: false});
    },
    //布局中字段修改
    bindChange(e){
      let detail = e.detail,
        field = detail.field,
        id = field.field_id || field.fieldName,
        type = field.type,
        val = detail.val,
        val2 = '',
        obj = this.data.inputData,
        {dtlMapField,entity} = this.data,
        isDtlMap = dtlMapField.indexOf(id) >= 0;  //主表字段映射明细表
      if (id === 'assist_account_json')return;  //辅助核算字段不操作

      if (type === 'num' || type === 'currency' || type === 'percent'){
        val = val ? val : null
      }
      console.log(val);
      //赋值
      this.data.inputData.entity[id] = val;
      this.data.defData[id] = val;
      //日期类型
      if (type === 'datetime'){
        let newVal = val;
        if (field.length === 'yyyy-MM') {
          newVal && (newVal = newVal + '-01')
        }else if (field.length === 'yyyy') {
          newVal && (newVal = newVal + '-01-01')
        }
        newVal && (this.data.inputData.entity[id] = newVal);
      }

      //单选引用-传入显示值，调用选择后操作（映射）
      if (type === 'reference1'){
        this.data.inputData.entity[id + ';value'] = field.entityVal;
        this.data.defData[id + ';value'] = field.entityVal;
        val2 = field.entityVal;
        val && this.selectReference(field,val);

        if (typeof val === 'object'){
          val = val.row_id;
          this.data.inputData.entity[id] = val;
          this.data.defData[id] = val;
        }
        //触发选择后过滤明细表数据
        this.setData({
          myMainEntity: [{
            mainEntity: field.mainEntity,
            rowid: val || ''
          }]
        })
      }

      // 231205 liang 地点
      if(type === 'location') {
        let { referenceFilterCondition, } = field,
          name = val.name,
          obj = {[id]:name};
        if(referenceFilterCondition) {  // 设置了映射
          try {
            referenceFilterCondition = JSON.parse(referenceFilterCondition)
            let { name, address, latitude, longitude, } = val,
                dataParse = {
                  addressField: address,
                  lngField: longitude,
                  latField: latitude,
                }
            Object.entries(referenceFilterCondition).forEach(([skey, tkey]) => {
              if(val) {
                // this.data.inputData.entity[tkey] = dataParse[skey]
                // this.data.defData[tkey] = dataParse[skey]
                if(val) obj[tkey] = dataParse[skey]
              }
            })
          } catch(err) {
            console.log('[JSON.parse(referenceFilterCondition) err]', err)
          }
        }
        //240309 yan 把赋值代码移出if代码块，没有映射时需要提交名称
        this.data.inputData.entity = { ...this.data.inputData.entity, ...obj, }
        let defEntity = { ...this.data.defData, ...obj, }
        this.setData({ isEdit: true, });
        this.setData({ defData: defEntity, });
        this.setData({ isEdit: false, });
      //  240309 end
      }

      //库存拆卸单中的出仓库、引用商品字段
      if (['goods_unit_quantity'].includes(id) && entity === 'disassembly_order') {
        this.getGoodsOutPrice();
      }

      //bom表带出商品数量修改
      if (['goods_unit_quantity','goods_quantity'].includes(id)){
        this.handleQuantity(val);
      }
      //商品字段清空bom表明细
      if (['quote_goods','reference1_goods'].includes(id) && !val){
        this.clearBomDetails();
      }

      //判断是否为主表映射明细表字段，是则循环明细更新明细数据值
      if (isDtlMap){
        this.setDtlMapping(id,val,val2);
      }
      //会计科目字段，选择后更新会计科目，判断辅助核算项目
      if (id === 'account_id') {  //会计科目
        this.setData({
          accountId: val
        })
      }

      //调用判断计算公式
      this.calculate(id);
    },
    //逻辑型字段修改
    switchChange(e){
      let {field} = e.currentTarget.dataset,
        detail = e.detail,
        id = field.field_id || field.fieldName;
      //赋值
      this.data.inputData.entity[id] = detail;
      this.data.defData[id] = detail;
    },
    //明细修改
    bindDetail(e){
      let detail = e.detail,
        data = detail.details,
        index = detail.index,
        tableid = detail.table_id,
        isDelete = detail.isDelete;
      let defDetail = this.data.defDetail,
        inputDetail = this.data.inputData.details,
        hasDetail = false;

      //循环所有明细
      wx.$each(defDetail,(i,item)=>{
        if (item.table_id === tableid){
          hasDetail = true;
          let entitys = item.entitys;
          if (index >= 0){
            if (isDelete){
              entitys.splice(index, 1);
              return
            }
            let entity = entitys[index].entity;
            entity = wx.$extend(entity,data.entity);
            item.entitys[index].entity = entity;
            item.entitys[index].details = data.details;
            // item.entitys[index].entity = data.entity;
          }else {
            item.entitys.push(data);
          }
        }
      });

      //没有明细
      if (!hasDetail){
        defDetail.push({
          table_id: tableid,
          entitys: [data]
        });
      }
      //显示明细
      this.setData({ defDetail: defDetail });

      //提交明细值过滤引用[**;value]字段
      let detailEntity = data && wx.$extend(data.entity);
      wx.$each(detailEntity,(key,val)=>{
        if (key.indexOf(';') >= 0){ delete detailEntity[key] }
      });
      console.log(data);
      let data2 = {
        details: data && data.details,
        entity: detailEntity
      };
      wx.$each(inputDetail,(i,item)=>{
        if (item.table_id === tableid){
          let entitys = item.entitys;
          if (index >= 0){
            if (isDelete){
              entitys.splice(index, 1);
              return
            }

            let entity = entitys[index].entity;
            entity = wx.$extend(entity,detailEntity);

            data2.entity = entity;
            entitys[index] = data2;
          }else {
            entitys.push(data2);
          }
        }
      });
      if (!hasDetail){
        inputDetail.push({
          table_id: tableid,
          entitys: [data2]
        })
      }
    },

    //改变按钮状态
    triggerBtnType(type){
      let obj = {};
      if (type === 'read'){ //只读
        obj = {
          editBtn: true,
          saveBtn: false,
          newBtn: false,
          disabled: true
        }
      }
      if (type === 'edit'){//编辑
        obj = {
          editBtn: false,
          saveBtn: true,
          newBtn: true,
          disabled: false,
          isEdit: false
        }
      }
      if (type === 'approve'){  //审批
        obj = {
          editBtn: false, //编辑按钮
          saveBtn: false,  //保存按钮
          newBtn: false,    //保存新增按钮
          disabled: true
        }
      }
      this.setData(obj);
    },

    //获取默认仓库
    async getDefaultWarehouse() {
      let defWarehouse = '';
      if (this.data.defWarehouse === undefined){
        let post = {
          "oby":"Warehouse.row_id desc",
          "table_id":"Warehouse",
          "page":1,
          "limit":1,
          "SearchWhere":[{"CompareWith":"Warehouse.is_default","Operator":"=","CompareValue": true,"or":0}]};
        await wx.$post(3,'DynamicQuery/query_dynamic_v1',post).then(res=>{
          if (res.errcode != 0)return;
          let data = res.data.row[0];
          if (data){
            defWarehouse = {
              name: data.warehouse_name,
              id: data.row_id
            }
            this.data.defWarehouse = defWarehouse;
          }
        })
      }else {
        defWarehouse = this.data.defWarehouse;
      }
      return defWarehouse;
    },

    //获取库存模块定义
    getStockEntity(){
      let url = 'DynamicQuery/query_dynamic_v1',
        post = {
          SearchWhere: [{
            CompareValue: this.data.entity,
            CompareWith: "stock_entity.table_id",
            Operator: "=",
            or: 0
          }],
          limit: 1,
          oby: "stock_entity.row_id desc",
          page: 1,
          table_id: "stock_entity",
        };
      return new Promise(resolve => {
        wx.$post(3,url,post).then(res=>{
          this.data.stockEntity = res.data.row[0];
          resolve();
        })
      })
    },


    //辅助核算
    assistChange(e){

      let assistData = e.detail,
        assistVal = {
          name: assistData.name.join(','),
          type: assistData.type.join(','),
          id: assistData.id.join(','),
        },
        {defData} = this.data;
      defData.assist_account_json = assistVal.name;
      // defData.assist_account_json = JSON.stringify(assistVal);
      this.data.inputData.entity.assist_account_json = JSON.stringify(assistVal);

      this.setData({isEdit: true})
      this.setData({
        assistFlag: true,
        assistData: e.detail,
        defData
      });
      this.setData({isEdit: false})
    },
    assistValid(e){
      let {assistFlag,assistData} = this.data,
        flag = true;
      if (!assistFlag)return true;
      this.setData({assistValidFlag: true});
      if (assistData.type.length !== assistData.id.length){
        flag = false;
        wx.$toast('请选项辅助核算！')
      }
      flag && wx.$each(assistData.id,(i,item)=>{
        if (!item){
          flag = false;
          wx.$toast('请选项辅助核算！');
          return false
        }
      });
      let assistVal = {
        name: assistData.name.join(','),
        type: assistData.type.join(','),
        id: assistData.id.join(','),
      };

      return flag;
    },

    //特殊模块特殊处理
    specialHandle(field,obj){
      let {entity} = this.data;

      //组装单、拆卸单
      if (['assembly_order','disassembly_order'].includes(entity)){
        //字段不可录入'goods_id','goods_unit_price','price','goods_model','quote_unit'
        if (['goods_id','goods_unit_price','price'].includes(field)){
          obj.isDisabled = true;
        }
      }
      //组装单自动分摊默认勾选
      if (entity === 'disassembly_order' && field === 'is_auto_share') {
        obj.defaultValue = true;
      }

    },

    //修改设置引用字段中条件
    setReferenceCondition(val,field,filter){
      let obj = filter && JSON.parse(filter);
      if (obj && obj.filters){  //字段已有有过滤数据
        let flag2 = true;
        wx.$each(obj.filters,(i,ite2)=>{
          if (ite2.fieldName === field && ite2.operator === '='){ //已有过滤条件则修改
            flag2 = false;
            if (val){ite2.value = val;return}//为空则删除
            obj.filters.splice(i,1);
          }
        });
        if (flag2){ //未过滤条件则添加条件
          val && obj.filters.push(
            {"type":"AND","fieldName": field,"value":val,"operator":"="}
          )
        }
      }else { //没有过滤条件
        val && (obj = {"filters":[{"type":"AND","fieldName": field,"value": val,"operator":"="}],"type":"AND"})
      }
      if (obj && !obj.filters.length) {obj = ''}
      filter = obj && JSON.stringify(obj);
      return filter
    }

  },

})
